// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);

// Cordova is ready
//
var db;

function onDeviceReady() {
	db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
}

function btnInfo_Click() {
	  var info = 	'Device Name: '     + device.name     + '<br />' + 
				    'Device Cordova: '  + device.cordova + '<br />' + 
				    'Device Platform: ' + device.platform + '<br />' + 
				    'Device UUID: '     + device.uuid     + '<br />' + 
				    'Device Model: '    + device.model     + '<br />' + 
				    'Device Version: '  + device.version  + '<br />';
	  $("#divContent").html(info);
}

function btnCreateDB_Click() {
    db.transaction(createDB, errorCB, successCB);
    $("#divLocalInput").show();
}

function btnSync_Click() {
	db.transaction(syncData, errorCB, successCB);
}

function btnInsert_Click() {
	db.transaction(insertData, errorCB, successCB);
}

function btnReSync_Click() {
	db.transaction(reSyncData, errorCB, successCB);
}

function btnDelete_Click() {
	db.transaction(dropDB, errorCB, successCB);
	$("#divLocalInput").hide();
	$("#divContent").empty();
}

function createDB(tx) {
    tx.executeSql('DROP TABLE IF EXISTS DEMO');
    tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
    selectData(tx);
}

function syncData(tx) {
	var curURL = "http://192.168.1.38:8989/mfscWS/services/UserAuthen/Sync_Data";
	var result = callDataService(curURL,"GET",'');
	if (result != '') {
		var jSonResult = JSON.parse(result);
		for (var i = 0; i < jSonResult.length; i++) {
			tx.executeSql('INSERT INTO DEMO (id, data) VALUES (?, ?)',[jSonResult[i].id,jSonResult[i].data]);
		}
		selectData(tx);
	}
}

function reSyncData(tx) {
	tx.executeSql('SELECT * FROM DEMO',[],querySuccessJson, errorCB);
}

function dropDB(tx) {
	tx.executeSql('DROP TABLE IF EXISTS DEMO');
}

function selectData(tx) {
	
	tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB);
}

function insertData(tx) {
	tx.executeSql('INSERT INTO DEMO(id,data) VALUES (11,"First Row")');
	tx.executeSql('INSERT INTO DEMO(id,data) VALUES (12,"SECOND ROW")');
    selectData(tx);
}

function querySuccess(tx, results) {
    var len = results.rows.length;
    var result = "DEMO table: " + len + " rows found.</br>";
    for (var i=0; i<len; i++){
    	result +=" ID = " + results.rows.item(i).id + " Data =  " + results.rows.item(i).data +"</br>";
    }
    $("#divContent").html(result);
}

function querySuccessJson(tx, results) {
    var len = results.rows.length;
    var strData = "[";
    for (var i=0; i<len; i++){
    	if (strData.length > 3) {
			strData += ",";
		}
    	strData += '{"id":"' + results.rows.item(i).id + '","data":"' + results.rows.item(i).data + '"}';
    }
    strData += "]";
    var curURL = "http://192.168.1.38:8989/mfscWS/services/UserAuthen/Sync_Data_Post";
	var result = callDataService(curURL,"POST",strData);
	if (result == 'ok') {
		alert("success!");
		 $("#divContent").html("success");
	} else {
		alert("fail!");
		$("#divContent").html("fail");
	}
}

function errorCB(tx, err) {
    alert("Error processing SQL: "+err);
}

function successCB() {
	//alert("Completed !");
}

function callDataService(curURL,type,strData) {
	var result = "";
	$.ajax({
        type: type,
        async: false,	
        url: curURL,
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        dataType: "xml",
        timeout: 30000,
        data: {syncData:strData},
        success: function (data, textStatus, jqXHR){  
        	result = $(data).text();
        } ,
        error: function (xhr, ajaxOptions, thrownError){  
            alert(xhr.status);          
            alert(thrownError);
        } 
    });
	return result;
}

//-----------------------------------------------
function reset_Click() {
	$("#txtId").val('');
	$("#txtData").val('');
	$("#txtId").focus();
}

function insert_Click() {
	if ($("#txtId").val()=='' || $("#txtId").val()=='undefined') {
		alert('Please, Input Id !');
		return;
	}
	
	if ($("#txtData").val()=='' || $("#txtData").val()=='undefined') {
		alert('Please, Input Data !');
		return;
	}
	// kiem tra trung id
	db.transaction(checkId, errorCB, successCB);
	alert("Completed!");
}

function checkId(tx) {
	var sql='SELECT count(id) FROM DEMO WHERE id = ' + $("#txtId").val();
	tx.executeSql(sql,[],querySuccessCheckId,errorCB);
}

function querySuccessCheckId(tx, results) {
	if (results.rows.length==0) {
		alert(" Id " + $("#txtId").val() + " existed ! ");
	} else {
		db.transaction(insertLocalData, errorCB, successCB);
	}
}

function insertLocalData(tx) {
	tx.executeSql('INSERT INTO DEMO (id, data) VALUES (?, ?)',[$("#txtId").val(),$("#txtData").val()]);
	selectData(tx);
}